<!--
 * @Version: 1.0
 * @Autor:
 * @Date: 2021-03-29 12:22:47
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-12-09 10:16:48
 * @Description:
-->
<template>
  <el-card class="app-container">
    <div v-loading="loading">
      <div>
        <el-form ref="formFieldsData" :model="formFieldsData" :rules="rules" inline>
          <div class="header_title_box">
            <h2>{{ title }}基本信息</h2>
            <div v-if="title === '销售订单' || title === '预售订单' || title === '客户订单'">
              <el-form ref="formNo" :model="selectData" size="medium">
                <el-form-item label="" style="margin-bottom: 0px;">
                  <!-- <el-select v-model="selectData.orderNo" filterable placeholder="请选择订单">
                    <el-option v-for="item in getAllOrderData" :key="item.id" :value="item.id" :label="item.order_no" />
                  </el-select> -->
                  <el-input v-model.trim="selectData.orderNo" placeholder="请选择订单编号" />
                </el-form-item>
                <el-form-item label="" style="margin-bottom: 0px;">
                  <el-button type="primary" @click="orderInfo(selectData.orderNo, 'add')">预 填</el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
          <div class="filter-selection">
            <el-form-item v-if="title !== '客户订单' && title !== '借卖订单'" label="平台订单号" :label-width="formLabelWidth" prop="platform_no">
              <el-input v-model.trim="formFieldsData.platform_no" :disabled="disabled" placeholder="请输入平台订单号" autocomplete="off" clearable style="width:247px" />
            </el-form-item>
            <el-form-item v-if="title === '客户订单' || title === '借卖订单'" label="平台订单号" :label-width="formLabelWidth">
              <el-input v-model.trim="formFieldsData.platform_no" :disabled="disabled" placeholder="请输入平台订单号" autocomplete="off" clearable style="width:247px" />
            </el-form-item>
            <el-form-item v-if="title !== '客户订单'" label="平台订单号2" :label-width="formLabelWidth" prop="platform_no_ext">
              <el-input v-model.trim="formFieldsData.platform_no_ext" :disabled="disabled" placeholder="请输入平台订单号" autocomplete="off" clearable style="width:247px" />
            </el-form-item>
            <el-form-item v-if="title !== '客户订单'" label="平台选择" :label-width="formLabelWidth" prop="platform_id">
              <el-select v-model="formFieldsData.platform_id" :disabled="disabled" placeholder="请选择平台" filterable clearable style="width:247px" @change="selectPlatform">
                <el-option v-for="item in optionpPlatform" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="title !== '客户订单'" label="店铺" :label-width="formLabelWidth" prop="shop_basics_id">
              <el-select v-model="formFieldsData.shop_basics_id" :disabled="disabled" placeholder="请选择店铺" filterable clearable style="width:247px" @change="selectShop">
                <el-option v-for="item in optionpShop" :key="item.id" :label="item.shop_name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="title==='客户订单'||title==='借卖订单'" label="选择客户" :label-width="formLabelWidth" prop="company_id">
              <el-select v-model="formFieldsData.company_id" :disabled="disabled" placeholder="请选择客户" filterable style="width:247px" @change="selectCompany">
                <el-option v-for="item in optionpCompany" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="title==='借卖订单'" label="订单发货类型" :label-width="formLabelWidth" prop="delivery_method">
              <el-select v-model="formFieldsData.delivery_method" :disabled="disabled" placeholder="请选择" style="width:247px">
                <el-option v-for="item in optionTypes" :key="item.value" :value="item.value" :label="item.label" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="formFieldsData.delivery_method==='1'" label="物流公司" :label-width="formLabelWidth" prop="shipping_name">
              <el-input v-model.trim="formFieldsData.shipping_name" :disabled="disabled" placeholder="请输入物流公司" autocomplete="off" clearable style="width:247px" />
            </el-form-item>
            <el-form-item v-if="formFieldsData.delivery_method==='1'" label="物流单号" :label-width="formLabelWidth" prop="shipping_code">
              <el-input v-model.trim="formFieldsData.shipping_code" :disabled="disabled" placeholder="请输入物流单号" autocomplete="off" clearable style="width:247px" />
            </el-form-item>
            <el-form-item v-if="title==='借卖订单'" label="结算单价" :label-width="formLabelWidth" prop="settlement_price">
              <el-input v-model.trim="formFieldsData.settlement_price" :disabled="disabled" placeholder="请输入结算单价" autocomplete="off" clearable style="width:247px" />
            </el-form-item>
            <el-form-item label="付款时间" :label-width="formLabelWidth" prop="paid_at">
              <el-date-picker v-model="formFieldsData.paid_at" :disabled="disabled" type="date" style="width:247px" value-format="timestamp" placeholder="选择日期时间" />
            </el-form-item>
            <el-form-item label="备注" :label-width="formLabelWidth" prop="remarks">
              <el-input v-model="formFieldsData.remarks" type="textarea" autosize :disabled="disabled" style="width:247px" placeholder="请输入备注" />
            </el-form-item>
          </div>
          <div class="header_title_box">
            <h2>
              <span class="mr-10">收货人信息</span>
              <span v-if="orderId" class="el-icon-edit-outline pointer blue" @click="disableAddress=!disableAddress" />
            </h2>
          </div>
          <div class="filter-selection">
            <el-form-item key="1address_name" label="买家姓名" :label-width="formLabelWidth" prop="address_name">
              <el-input v-model="formFieldsData.address_name" name="address_name" :disabled="disableAddress" placeholder="请输入买家姓名" autocomplete="off" clearable style="width:247px" @input="inputChange" />
            </el-form-item>
            <!-- 买家的邮箱 -->
            <el-form-item label="买家邮箱" :label-width="formLabelWidth" prop="address_email">
              <el-input v-model.trim="formFieldsData.address_email" :disabled="disableAddress" placeholder="请输入买家邮箱" autocomplete="off" clearable style="width:247px" @input="inputChange" />
            </el-form-item>
            <!-- 买家电话 -->
            <el-form-item label="买家电话" :label-width="formLabelWidth" prop="address_phone">
              <el-input v-model.trim="formFieldsData.address_phone" :disabled="disableAddress" placeholder="请输入买家电话" autocomplete="off" clearable style="width:247px" @input="inputChange" />
            </el-form-item>
            <!-- 买家的国家的代码 -->
            <el-form-item label="国家" :label-width="formLabelWidth" prop="address_country">
              <el-select v-model="formFieldsData.address_country" :disabled="disableAddress" placeholder="请选择国家" filterable clearable style="width:247px">
                <el-option v-for="item in optionpCountry" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <!-- 买家的州/省（英文简写缩写） -->
            <el-form-item label="州/省" :label-width="formLabelWidth" prop="address_stateorprovince">
              <el-select v-model="formFieldsData.address_stateorprovince" :disabled="disableAddress" placeholder="请选择州/省" filterable clearable style="width:247px" @change="changeState">
                <el-option v-for="item in optionStates" :key="`${item.id}States`" :label="`${item.code}(${item.cname})`" :value="item.code" />
              </el-select>
            </el-form-item>
            <!-- 买家的城市 (英文全称) address_cityname-->
            <el-form-item label="城市" :label-width="formLabelWidth" prop="address_cityname">
              <el-select v-model="formFieldsData.address_cityname" :disabled="disableAddress" placeholder="请选择城市" filterable clearable style="width:247px" @change="changeCity">
                <el-option v-for="item in optionCity" :key="`${item.id}city`" :label="`${item.name}(${item.cname})(${item.code})`" :value="item.lower_name" />
              </el-select>
            </el-form-item>
            <!-- 买家的邮编 -->
            <el-form-item label="邮编" :label-width="formLabelWidth" prop="address_postalcode">
              <el-select v-model="formFieldsData.address_postalcode" :disabled="disableAddress" placeholder="请选择邮编" filterable clearable style="width:247px" @change="inputChange">
                <el-option v-for="item in optionPostalCode" :key="item.zip" :label="item.zip" :value="item.zip" />
              </el-select>
            </el-form-item>
            <!-- 买家的街道1 -->
            <el-form-item label="街道1" :label-width="formLabelWidth" prop="address_street1">
              <el-input v-model.trim="formFieldsData.address_street1" :disabled="disableAddress" placeholder="请输入街道1" autocomplete="off" clearable style="width:247px" @input="inputChange" />
            </el-form-item>
            <!-- 买家的街道2 -->
            <el-form-item label="街道2" :label-width="formLabelWidth" prop="address_street2">
              <el-input v-model.trim="formFieldsData.address_street2" :disabled="disableAddress" placeholder="请输入街道2" autocomplete="off" clearable style="width:247px" @input="inputChange" />
            </el-form-item>
            <!-- 买家的街道3 -->
            <el-form-item label="街道3" :label-width="formLabelWidth" prop="address_street3">
              <el-input v-model.trim="formFieldsData.address_street3" :disabled="disableAddress" placeholder="请输入街道3" autocomplete="off" clearable style="width:247px" @input="inputChange" />
            </el-form-item>
          </div>
        </el-form>
        <div class="header_title_box">
          <h2>
            <span class="mr-10">商品信息</span>
            <span v-if="orderId" class="el-icon-edit-outline pointer blue" @click="disableProduct=!disableProduct" />
          </h2>
        </div>
        <div>
          <div v-if="!orderId && title==='销售订单'" class="mtb">
            <el-radio-group v-model="formFieldsData.product_type" @change="changeProduct">
              <el-radio label="1">普通商品</el-radio>
              <el-radio label="2">组合商品</el-radio>
            </el-radio-group>
          </div>
          <el-form ref="formData" :rules="model.rules" :model="model" class="dialog-form-expand3">
            <el-table :data="model.fields" tooltip-effect="dark" style="width: 100%" border fit>
              <el-table-column v-if="title!=='客户订单'&& title!=='借卖订单'" align="center" label="选择商品" width="200px">
                <template slot-scope="field" v-loading="loadingProduct">
                  <el-form-item :prop="'fields.' + field.$index + '.sku'" :rules="model.rules.sku">
                    <el-select v-model="field.row.sku" :disabled="disableProduct" size="small" placeholder="请选择商品" filterable clearable @change="changeGoods">
                      <!-- // :disabled="title==='预售订单' ? !item.is_presale: item.is_presale" -->
                      <el-option v-for="item in productData" :key="`${item.code}(${item.name_ch}/${item.platform_code}/${item.is_presale_text})`" :label="`${item.code}(${item.name_ch}/${item.platform_code})`" :value="item.platform_code" />
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <!-- 客户选择商品 -->
              <el-table-column v-if="title==='客户订单'|| title==='借卖订单'" align="center" label="选择商品" width="200px">
                <template slot-scope="field" v-loading="loadingProduct">
                  <el-form-item :prop="'fields.' + field.$index + '.sku'" :rules="model.rules.sku">
                    <el-select v-model="field.row.sku" :disabled="disableProduct" size="small" placeholder="请选择商品" filterable clearable @change="changeGoods">
                      <el-option v-for="(item, index) in productData" :key="`${item.code}(${item.name_ch}${index}`" :label="`${item.code}(${item.name_ch})`" :value="item.code" />
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column align="center" label="数量">
                <template slot-scope="field">
                  <el-form-item :prop="'fields.' + field.$index + '.quantity_purchased'" :rules="model.rules.quantity_purchased">
                    <el-input v-model.trim="field.row.quantity_purchased" :disabled="disabled" size="small" placeholder="输入数量" autocomplete="off" clearable />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column v-if="title !== '客户订单' && title!=='借卖订单'" align="center" label="单价">
                <template slot-scope="field">
                  <el-form-item :prop="'fields.' + field.$index + '.transaction_price_value'" :rules="model.rules.transaction_price_value">
                    <el-input v-model.trim="field.row.transaction_price_value" :disabled="disabled" size="small" placeholder="输入单价" autocomplete="off" clearable />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column v-if="title !== '客户订单' && title!=='借卖订单'" align="center" label="税费">
                <template slot-scope="field">
                  <el-form-item :prop="'fields.' + field.$index + '.tax_amount_value'" :rules="model.rules.tax_amount_value">
                    <el-input v-model.trim="field.row.tax_amount_value" :disabled="disabled" size="small" placeholder="输入税费" autocomplete="off" clearable />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column v-if="formFieldsData.product_type==='1'" align="center" label="商品类型">
                <template slot-scope="field">
                  <el-form-item v-if="field.row.sku">
                    <span v-if="title!=='客户订单' && title!=='借卖订单'"> 是否促销：{{ field.row.is_sales === true ? '是' : '-' }}</span>
                    <el-divider v-if="title!=='客户订单' && title!=='借卖订单'" />
                    <span>商品类型：{{ field.row.type===0 ? '内部商品' : '客户商品' }}</span>
                    <el-divider />
                    <span>包装方式：{{ field.row.packing_method ===1 ? '普通商品' : '多箱包装' }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column align="center" label="缩略图">
                <template slot-scope="field">
                  <el-form-item v-if="field.row.image_url">
                    <el-image :src="field.row.image_url" style="width:50px; height:50px" fit="contain" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column align="center" label="系统sku" prop="goods_code" />
              <el-table-column align="center" label="商品名称" prop="name_ch" />
              <el-table-column align="center" label="商品分类" prop="category_name" />
              <el-table-column align="center" label="币别">
                <template slot-scope="field">
                  <el-form-item>
                    <span>{{ field.row.transaction_price_currencyid }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
            </el-table>
            <div v-if="title!=='客户订单' && title!=='借卖订单'" class="total_box">
              <span>合计金额(USD)：</span>
              <!-- <app-price :price="fucaccMul(model.fields[0].transaction_price_value, model.fields[0].quantity_purchased)" /> -->
              <!-- <span>{{ fucaccMul(model.fields[0].transaction_price_value, model.fields[0].quantity_purchased) }}</span> -->
              <span v-if="!orderId">
                <app-price :price="includingTax(model.fields[0])" />
              </span>
              <app-price v-else :price="fucAccAdd(model.fields[0].tax_amount_value, fucaccMul(model.fields[0].transaction_price_value,model.fields[0].quantity_purchased))" />
            </div>
          </el-form>
        </div>
        <div class="footer-center">
          <el-button @click="handleCancelPath">取 消</el-button>
          <el-button :loading="formVisible" type="primary" @click="handleSubmitNew('formFieldsData')">确 定</el-button>
        </div>
      </div>
    </div>
  </el-card>
</template>

<script>
import {
  platformList,
  shopList,
  statesList,
  cityList,
  cityPostalCode,
  productsList,
  getCompanyList,
  orderCustomerProduct,
  getBorrowSellShopList,
  // getBorrowSellCompanyList,
  getBorrowSellGoodsList,
  combinationProductList
  //   getAllOrder
} from '@/utils/publicData'
import {
  accMul,
  accAdd
} from '@/utils/index'
export default {
  name: 'OrderRecordsAdd',
  data() {
    return {
      getAllOrderData: [],
      selectData: {
        orderNo: ''
      },
      optionTypes: [
        {
          value: '0',
          label: '平台自发'
        },
        {
          label: '客户发货',
          value: '1'
        }
      ],
      optionpCompany: [],
      title: '',
      disableProduct: false,
      loading: false,
      disableAddress: false,
      disabled: false,
      orderId: '',
      formVisible: false,
      formName: 'orderForm',
      formLabelWidth: '150px',
      formFieldsData: {
        product_type: '1',
        order_type: '0', // 0-销售订单 2-借卖订单; 3-客户订单
        platform_no: '',
        platform_id: '',
        platform: '',
        shop_basics_id: '',
        company_id: '',
        paid_at: '',
        remarks: '', // 备注
        address_name: '',
        buyer_firstname: '',
        buyer_lastname: '',
        address_email: '',
        address_phone: '',
        address_postalcode: '',
        address_country: '',
        address_country_name: '',
        address_stateorprovince: '',
        address_cityname: '',
        address_street1: '',
        address_street2: '',
        address_street3: '',
        settlement_price: '', // 结算单价
        shipping_code: '', // 快递运单号
        delivery_method: '0', // 借卖订单发货类型
        shipping_name: '' // 物流公司名称
      },
      path: {
        '销售订单': '/order/orderRecords',
        '异常订单': '/order/orderAbnormal',
        '借卖订单': '/order/orderBorrowSell',
        '客户订单': '/order/orderCustomer',
        '预售订单': '/order/orderPresale',
        'FBA订单': '/order/orderFba'
      },
      optionpShop: [],
      optionpPlatform: [],
      optionpCountry: [{
        value: 'US',
        label: 'United States'
      }],
      optionStates: [],
      optionCity: [],
      optionPostalCode: [],
      rules: {
        delivery_method: [
          {
            required: true,
            message: '请选择发货类型',
            trigger: 'change'
          }
        ],
        shipping_name: [
          {
            required: true,
            message: '请输入物流公司名称',
            trigger: 'blur'
          }, {
            min: 1,
            max: 50,
            message: '长度在 1 到 50 个字符',
            trigger: 'blur'
          }
        ],
        shipping_code: [
          {
            required: true,
            message: '请输入快递运单号',
            trigger: 'blur'
          }, {
            min: 1,
            max: 50,
            message: '长度在 1 到 50 个字符',
            trigger: 'blur'
          }
        ],
        settlement_price: [
          {
            required: true,
            message: '结算单价',
            trigger: 'blur'
          },
          { pattern: /\d+(\.[0-9]{1,2}){0,1}$/, message: '只能输入数字,最多二位小数', trigger: 'change' }
        ],
        company_id: [
          {
            required: true,
            message: '请选择客户',
            trigger: 'change'
          }
        ],
        platform_no: [{
          required: true,
          message: '请输入订单编号',
          trigger: 'blur'
        }, {
          min: 1,
          max: 30,
          message: '长度在 1 到 30 个字符',
          trigger: 'blur'
        }],
        platform_id: [{
          required: true,
          message: '请选择平台',
          trigger: 'blur'
        }],
        shop_basics_id: [{
          required: true,
          message: '请选择店铺',
          trigger: 'blur'
        }],
        // paid_at: [{
        //   required: true,
        //   message: '请选择付款时间',
        //   trigger: 'blur'
        // }],
        remarks: [{
          max: 500,
          message: '备注必须在500个字符以内',
          trigger: 'blur'
        }],
        address_name: [{
          required: true,
          message: '请输入姓名',
          trigger: 'change'
        },
        {
          required: true,
          pattern: /^[\u4e00-\u9fa5a-zA-Z0-9 ]+$/,
          message: '字符且不能存在特殊字符',
          trigger: 'blur'
        },
        {
          required: true,
          min: 1,
          max: 30,
          message: '长度在 1 到 20 个字符且不能存在特殊字符',
          trigger: 'blur'
        }],
        buyer_lastname: [{
          required: true,
          message: '请输入姓',
          trigger: 'blur'
        }, {
          min: 1,
          max: 30,
          message: '长度在 1 到 20 个字符',
          trigger: 'blur'
        }],
        address_email: [{
          required: false,
          message: '请输入邮箱地址',
          trigger: 'blur'
        }, {
          type: 'email',
          message: '请输入正确的邮箱地址',
          trigger: ['blur', 'change']
        }],
        address_phone: [{
          required: true,
          message: '请输入电话',
          trigger: 'blur'
        },
        {
          min: 10,
          message: '电话最少10位',
          trigger: 'blur'
        }
        ],
        address_country: [{
          required: true,
          message: '请选择国家',
          trigger: ['change', 'blur']
        }],
        address_stateorprovince: [{
          required: true,
          message: '请选择州/省',
          trigger: ['change', 'blur']
        }],
        address_cityname: [{
          required: true,
          message: '请选择城市',
          trigger: ['change', 'blur']
        }],
        address_postalcode: [{
          required: true,
          message: '请选择邮编',
          trigger: ['change', 'blur']
        }],
        address_street1: [{
          required: true,
          message: '请输入街道',
          trigger: ['change', 'blur']
        }]
      },
      model: {
        rules: {
          sku: [{
            required: true,
            message: '必填字段',
            trigger: 'change'
          }],
          quantity_purchased: [{
            required: true,
            message: '必填字段',
            trigger: 'blur'
          }, {
            pattern: /^[0-9]*$/,
            message: '只能输入数字',
            trigger: 'change'
          }],
          transaction_price_value: [
            {
              required: true,
              message: '必填字段',
              trigger: 'blur'
            },
            { pattern: /\d+(\.[0-9]{1,2}){0,1}$/, message: '只能输入数字,最多二位小数', trigger: 'change' }
          ]
        },
        fields: [this.getColumn()]
      },
      productData: [],
      sku: '',
      company_name: '',
      productData_01: [],
      productData_02: [],
      loadingProduct: false

    }
  },
  created() {
    this.title = this.$route.query.title
    platformList().then((data) => {
      this.optionpPlatform = data.map((arr) => {
        if (this.title === '借卖订单') {
          if (arr.id === 11) {
            arr.disabled = false
          } else {
            arr.disabled = true
          }
        } else {
          if (arr.id === 11) {
            arr.disabled = true
          } else {
            arr.disabled = false
          }
        }
        return arr
      })
      if (this.title === '借卖订单') {
        this.formFieldsData.platform_id = 11
        getBorrowSellShopList().then((data) => {
          this.optionpShop = data
        })
        // getBorrowSellCompanyList().then((data) => {
        //   this.optionpCompany = data
        // })
        // getCompanyList
        getCompanyList().then((data) => {
          this.optionpCompany = data
        })
        getBorrowSellGoodsList().then((data) => {
          this.productData = data.map((arr) => {
            arr.sku = arr.code
            arr.category_name = arr.category_name1
            return arr
          })
        })
      }
    })
    statesList().then((data) => {
      this.optionStates = data
      this.title = this.$route.query.title
      this.orderId = this.$route.query.id ?? ''
      if (this.orderId) {
        this.disabled = true
        this.disableAddress = true
        this.disableProduct = true
        this.orderInfo(this.orderId)
      } else {
        // let routeList = this.$store.state.tagsView.routeListViews
        // routeList.forEach(v => {
        //   if (v.path === this.$route.path) {
        //     if (v.formFieldsData) this.formFieldsData = v.formFieldsData
        //     if (this.formFieldsData.platform_id) this.selectPlatform(this.formFieldsData.platform_id)
        //     if (v.model) this.model = v.model
        //   }
        // })
        // this.formFieldsData = {}
      }
      if (this.title === '客户订单') {
        getCompanyList().then((data) => {
          this.optionpCompany = data
        })
      }
    })
    if (!this.$route.query.id) {
      // 获取所有订单
      //   getAllOrder().then((data) => {
      //     this.getAllOrderData = data
      //     console.log('==============')
      //   })
      const dataObj = window.localStorage.getItem('saleOrder')
      const saleOrderModel = window.localStorage.getItem('saleOrderModel')
      // window.localStorage.removeItem('saleOrder')
      if (dataObj) {
        const dataObjOld = JSON.parse(dataObj)
        this.formFieldsData = { ...dataObjOld }
        if (this.formFieldsData.platform_id) {
          // this.getVirtualWarehouseList()
          this.selectPlatform(this.formFieldsData.platform_id)
          this.formFieldsData.shop_basics_id = dataObjOld.shop_basics_id
          this.selectShop(dataObjOld.shop_basics_id)
          this.formFieldsData.sku = dataObjOld.sku
          this.model.fields = JSON.parse(saleOrderModel)
        }
        if (this.title === '客户订单') {
          this.selectCompany(dataObjOld.company_id)
          this.model.fields = JSON.parse(saleOrderModel)
        }
      }
    }
  },
  beforeDestroy() {
    if (!this.$route.params.id) {
      window.localStorage.setItem('saleOrder', JSON.stringify(this.formFieldsData))
      window.localStorage.setItem('saleOrderModel', JSON.stringify(this.model.fields))
    }
  },
  beforeRouteLeave(to, from, next) {
    if (!this.$route.query.id) {
      const routeList = this.$store.state.tagsView.routeListViews
      routeList.forEach(v => {
        if (v.path === this.$route.path) {
          v.formFieldsData = this.formFieldsData
          v.model = this.model
        }
      })
      this.$store.commit('tagsView/SET_ROUTE_LIST_VIEWS', routeList)
    }
    this.$nextTick(() => {
      next()
    })
  },
  methods: {
    changeProduct(id) {
      const vm = this
      vm.productData = []
      vm.formFieldsData.sku = ''
      vm.model.fields = [this.getColumn()]
      if (this.formFieldsData.product_type === '2') {
        vm.productData = vm.productData_02
      } else {
        vm.productData = vm.productData_01
      }
      console.log('vm.productData', vm.productData)
    },
    // 选择客户
    selectCompany(value) {
      if (this.title !== '借卖订单') {
        orderCustomerProduct(value).then((data) => {
          this.productData = data.map((arr) => {
            arr.sku = arr.code
            return arr
          })
        })
      }
    },
    // 获取选择店铺的客户
    getUpCompany(shopId) {
      return this.optionpShop.filter((item) => {
        return item.id === shopId
      })[0].company_name
    },
    inputChange(val) {
      this.$forceUpdate()
    },
    // 详情
    orderInfo(idOld, type = '') {
      console.log('id', idOld)
      // const id = idOld.replace(/\s*/g, '')
      const id = idOld
      if (!id) {
        return false
      }
      this.loading = true
      this.$http.get(`/orderRecords/${id}`).then((res) => {
        if (res.code === 10000) {
          const dataObj = res.data
          if (this.title === '销售订单' && dataObj.order_type !== 0 && dataObj.order_type !== 4) {
            this.$message.info('搜索订单只能是正常订单或预售订单')
            this.loading = false
            return false
          }
          if (this.title === '客户订单' && dataObj.order_type !== 3) {
            this.$message.info('搜索订单只能是客户订单')
            this.loading = false
            return false
          }
          this.selectPlatform(dataObj.platform_id)
          dataObj.paid_at = dataObj.paid_at * 1000
          dataObj.delivery_method = dataObj.delivery_method + ''
          this.formFieldsData.order_type = dataObj.order_type
          this.formFieldsData.platform_no = dataObj.platform_no
          this.formFieldsData.platform_id = dataObj.platform_id
          this.formFieldsData.platform = dataObj.platform
          this.formFieldsData.shop_basics_id = dataObj.shop_basics_id
          this.formFieldsData.company_id = dataObj.company_id
          this.formFieldsData.remarks = dataObj.remarks
          this.formFieldsData.paid_at = dataObj.paid_at
          this.formFieldsData.settlement_price = dataObj.settlement_price
          this.formFieldsData.shipping_code = dataObj.shipping_code
          this.formFieldsData.delivery_method = dataObj.delivery_method
          this.formFieldsData.shipping_name = dataObj.shipping_name
          this.formFieldsData.buyer_firstname = dataObj.product[0].buyer_user_firstname
          this.formFieldsData.buyer_lastname = dataObj.product[0].buyer_user_lastname
          this.formFieldsData.address_email = dataObj.address[0].address_email
          this.formFieldsData.address_phone = dataObj.address[0].address_phone
          this.formFieldsData.address_country = dataObj.address[0].address_country
          this.changeState(dataObj.address[0].ship_stateorprovince || dataObj.address[0].address_stateorprovince)
          this.formFieldsData.address_country_name = dataObj.address[0].address_country_name
          this.formFieldsData.address_stateorprovince = dataObj.address[0].address_stateorprovince
          this.formFieldsData.address_name = dataObj.address[0].address_name
          //  this.changeCity(dataObj.address[0].address_cityname)
          this.formFieldsData.address_cityname = dataObj.address[0].address_cityname
          this.formFieldsData.address_street1 = dataObj.address[0].address_street1
          this.formFieldsData.address_street2 = dataObj.address[0].address_street2
          this.formFieldsData.address_street3 = dataObj.address[0].address_street3
          this.formFieldsData.address_postalcode = dataObj.address[0].address_postalcode
          this.selectShop(dataObj.shop_basics_id)
          if (this.title === '客户订单' || this.title === '借卖订单') {
            this.selectCompany(dataObj.company_id)
          }
          setTimeout(() => {
            // this.changeGoods(dataObj.product[0].goods_id)
            this.sku = dataObj.product[0].sku
            this.formFieldsData.sku = dataObj.product[0].sku ? dataObj.product[0].sku : dataObj.product[0].goods_code
            this.model.fields = [{
              'goods_code': dataObj.product[0].goods_code,
              'goods_id': dataObj.product[0].goods_id,
              'name': dataObj.product[0].goods_name,
              'name_ch': dataObj.product[0].goods_name,
              'category_name': dataObj.product[0].category_name,
              'transaction_price_currencyid': 'USD',
              'transaction_price_value': dataObj.product[0].transaction_price_value,
              'quantity_purchased': dataObj.product[0].quantity_purchased,
              'tax_amount_currencyid': 'USD',
              'tax_amount_value': dataObj.product[0].tax_amount_value,
              'sku': dataObj.product[0].goods_code ? dataObj.product[0].goods_code : dataObj.product[0].sku,
              'image_url': dataObj.product[0].goods_pic,
              'goods_tax_amount': dataObj.product[0].goods_tax_amount ?? 0,
              'goods_price': dataObj.product[0].goods_price,
              'packing_method': dataObj.product[0].packing_method,
              'type': dataObj.product[0].type
            }]
            this.loading = false
          }, 1000)
        } else {
          this.loading = false
          this.$message.error(res.message)
        }
      }).catch(() => {
        this.loading = false
      })
    },
    includingTax(data) {
      //   const tariff = accMul(accMul(data.quantity_purchased, data.transaction_price_value, 4), (data.tax_tariff_rate /
      //       100), 4)
      //   const value = accMul(data.transaction_price_value, data.quantity_purchased, 4)
      //   const total = accAdd(tariff, value, 4)
      const total = accMul(accAdd(data.transaction_price_value, data.tax_amount_value, 4), data.quantity_purchased, 4)
      return total
    },
    fucAccAdd(val1, val2) {
      return accAdd(val1, val2)
    },
    // 税费
    fucTax(data) {
      const tariff = accMul(accMul(data.quantity_purchased, data.goods_price, 4), (data.tax_tariff_rate /
        100), 4)
      return tariff
    },
    fucaccMul(val1, val2) {
      return accMul(val1, val2)
    },
    changeGoods(value) {
      // console.log('======value====', value, this.productData)
      const dataObj = this.productData.filter((item) => {
        return item.sku === value
      })
      if (this.title === '编辑订单') {
        this.model.fields[0]['goods_code'] = dataObj[0].code
        this.model.fields[0]['goods_id'] = dataObj[0].id
        this.model.fields[0]['sku'] = dataObj[0].code
        this.formFieldsData['sku'] = dataObj[0].code
      } else {
        let goods_price = 0
        // console.log('========dataObj[0]=====', dataObj[0])
        if (this.formFieldsData.product_type === '2') {
          goods_price = dataObj[0]['price_usd']
        } else {
          goods_price = dataObj[0].is_sales ? dataObj[0].dataSales.sales_price : (dataObj[0].type ===
            1 ? dataObj[0].purchase_price_usd : dataObj[0].benchmark_price)
        }
        this.model.fields = [{
          'goods_code': dataObj[0].code,
          'goods_id': dataObj[0].id,
          'name': dataObj[0].name_en,
          'name_ch': dataObj[0].name_ch,
          'category_name': dataObj[0].category_name,
          'transaction_price_currencyid': 'USD',
          'goods_price': goods_price,
          'quantity_purchased': 1,
          'tax_amount_currencyid': 'USD',
          'tax_amount_value': 0.00,
          'tax_tariff_rate': dataObj[0].tax_tariff_rate,
          'sku': dataObj[0].platform_code ?? dataObj[0].code,
          'image_url': dataObj[0].image_url,
          'is_sales': dataObj[0].is_sales,
          'type': dataObj[0].type,
          'packing_method': dataObj[0].packing_method,
          'transaction_price_value': '',
          'goods_tax_amount': '',
          'product_code': dataObj[0].sku
        }]
      }
    },
    // 可选择商品列表
    getColumn() {
      return {
        'goods_code': '',
        'goods_id': '',
        'name': '',
        'sku': '',
        'transaction_price_currencyid': '-', // 商品交易价格(单位)
        'transaction_price_value': '', // 商品交易价格
        'quantity_purchased': 1,
        'tax_amount_currencyid': '-', // 税额(单位)
        'tax_amount_value': 0.00, // 税额
        'tax_tariff_rate': 0.00,
        'goods_price': 0.00,
        'goods_tax_amount': 0.00,
        'product_code': ''
      }
    },
    // tax_tariff_rate
    // 选择店铺
    selectShop(val) {
      const vm = this
      if (!val || this.title === '借卖订单') return
      vm.productData = []
      vm.formFieldsData.sku = ''
      vm.model.fields = [this.getColumn()]
      vm.loadingProduct = true
      productsList(val).then((data) => {
        // 过滤预售商品
        vm.productData_01 = data.filter((arr) => {
          arr.is_presale_text = arr.is_presale ? '预售' : ''
          if (this.title === '客户订单') {
            return arr.is_presale === false && arr.type === 1
          } else if (this.title === '销售订单') {
            return arr.type !== 1
          } else {
            return arr.is_presale === false && arr.type !== 1
          }
        })
        // 普通商品
        if (this.formFieldsData.product_type === '1') {
          vm.productData = vm.productData_01
        }
        this.loadingProduct = false
      })
      // 组合商品
      combinationProductList(val).then((data) => {
        vm.productData_02 = data.map((arr) => {
          arr.platform_code = arr.sku
          return arr
        })
        // 组合商品
        if (this.formFieldsData.product_type === '2') {
          vm.productData = vm.productData_02
        }
      })
    },
    // 修改省份
    changeState(value) {
      const address_stateorprovince = this.optionStates.filter((arr) => {
        return arr.code === value
      })
      // 清空 城市 邮编
      this.formFieldsData.address_postalcode = ''
      this.formFieldsData.address_cityname = ''
      this.optionCity = []
      this.optionPostalCode = []
      cityList(address_stateorprovince[0].id).then(data => {
        this.optionCity = data
      })
    },
    // 城市
    changeCity(value) {
      const obj = this.optionCity.filter((arr) => {
        return arr.lower_name === value
      })
      this.formFieldsData.address_postalcode = ''
      this.optionPostalCode = []
      cityPostalCode(obj[0].id).then(data => {
        this.optionPostalCode = data.sort((a, b) => {
          return a.zip - b.zip
        })
      })
    },
    // 选择平台
    selectPlatform(val) {
      const vm = this
      if (!val) return
      vm.formFieldsData.shop_basics_id = ''
      vm.optionpShop = []
      shopList(val).then((data) => {
        vm.optionpShop = data
      })
    },
    // 选择店铺 productsList

    // 取消
    handleCancelPath() {
      this.$router.go(-1)
    },
    // 提交
    handleSubmitNew(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$refs['formData'].validate((validSon) => {
            if (validSon) {
              this.formVisible = true
              // 编辑
              if (this.orderId) {
                if (this.formFieldsData.sku !== this.sku) {
                  this.$confirm('提交商品与原始商品不一致，确认修改', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                  }).then(() => {

                  }).catch(() => {
                    return false
                  })
                }
                this.$http.put(`orderRecords/${this.orderId}`, this.getDataEdit()).then(response => {
                  if (response.code === 10000) {
                    this.$message.success('编辑成功')
                    this.formVisible = false
                    this.handleCancelPath()
                  } else {
                    this.$message.error(response.message)
                  }
                }).catch(() => {
                  this.formVisible = false
                })
              } else {
                this.$http.post('orderRecords', this.getData()).then(response => {
                  if (response.code === 10000) {
                    this.$message.success('添加成功')
                    this.formVisible = false
                    this.handleCancelPath()
                  } else {
                    this.$message.error(response.message)
                  }
                }).catch(() => {
                  this.formVisible = false
                })
              }
            }
          })
        } else {
          return false
        }
      })
    },
    // 编辑参数
    getDataEdit() {
      const obj = Object.assign({}, this.formFieldsData)
      const address = {}
      address.address_name = obj.address_name
      address.buyer_firstname = obj.buyer_firstname
      address.buyer_lastname = obj.buyer_lastname
      address.address_email = obj.address_email
      address.address_phone = obj.address_phone
      address.address_postalcode = obj.address_postalcode
      address.address_country = obj.address_country
      const address_country_name1 = this.optionpCountry.filter((item) => {
        return item.value === obj.address_country
      })
      address.address_country_name = address_country_name1[0].label
      address.address_stateorprovince = obj.address_stateorprovince
      address.address_cityname = obj.address_cityname
      address.address_street1 = obj.address_street1
      address.address_street2 = obj.address_street2
      address.address_street3 = obj.address_street3
      address.goods_code = this.model.fields[0].goods_code
      address.goods_id = this.model.fields[0].goods_id
      address.name = this.model.fields[0].name
      return address
    },
    // 获取添加参数
    getData() {
      const obj = Object.assign({}, this.formFieldsData)
      const data = {}
      data.product_type = obj.product_type
      data.order_type = this.title === '销售订单' ? 0 : (this.title === '借卖订单' ? 2 : (this.title === '客户订单' ? 3 : 5))
      data.platform_no = obj.platform_no
      data.platform_no_ext = obj.platform_no_ext
      data.delivery_method = obj.delivery_method
      data.shipping_code = obj.shipping_code
      data.settlement_price = obj.settlement_price
      data.shipping_name = obj.shipping_name
      data.company_id = obj.company_id ?? 0
      data.total_num = this.model.fields[0].quantity_purchased || 1
      data.total_price = this.includingTax(this.model.fields[0]) || 0
      if (this.title !== '客户订单') {
        data.platform_id = obj.platform_id
        const platform = this.optionpPlatform.filter((item) => {
          return item.id === obj.platform_id
        })
        data.platform = platform[0].name
        data.shop_basics_id = obj.shop_basics_id
        const shop_name = this.optionpShop.filter((item) => {
          return item.id === obj.shop_basics_id
        })
        data.shop_name = shop_name[0].shop_name
      }

      data.paid_at = obj.paid_at / 1000
      data.remarks = obj.remarks
      const address = {}
      address.address_name = obj.address_name
      address.buyer_firstname = obj.buyer_firstname
      address.buyer_lastname = obj.buyer_lastname
      address.address_email = obj.address_email
      address.address_phone = obj.address_phone
      address.address_postalcode = obj.address_postalcode
      address.address_country = obj.address_country
      const address_country_name1 = this.optionpCountry.filter((item) => {
        return item.value === obj.address_country
      })
      address.address_country_name = address_country_name1[0].label
      address.address_stateorprovince = obj.address_stateorprovince
      address.address_cityname = obj.address_cityname
      address.address_street1 = obj.address_street1
      address.address_street2 = obj.address_street2
      address.address_street3 = obj.address_street3
      data.address = [address]
      if (!this.model.fields[0].tax_amount_value) {
        this.model.fields[0].tax_amount_value = 0
      }
      const fieldsProduct = Object.assign(this.model.fields)
      if (this.title !== '借卖订单') {
        fieldsProduct[0].goods_tax_amount = this.fucTax(fieldsProduct[0]) ?? 0
      }
      data.product = fieldsProduct
      if (this.title === '销售订单') {
        if (!data.product[0].goods_tax_amount) {
          data.product[0].goods_tax_amount = 0
        }
      }

      return data
    }
  }
}

</script>

<style lang="scss" scoped>
.total_box {
  margin: 30px 0 0 10px;
}
</style>
